package com.schoolMall.interceptor;

import com.schoolMall.domain.User;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * @author:zyh
 * @Time:2021-09-04-16:49
 * @email:1269231889@qq.com
 */
public class ShopLoginInterceptor extends HandlerInterceptorAdapter {
    /**
     * 主要做controller前拦截，即用户操作发生前，改写preHandler里的逻辑，进行拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object userReq = request.getSession().getAttribute("user");
        if (Objects.nonNull(userReq)) {
            User user = (User) userReq;
            if (Objects.nonNull(user) && Objects.nonNull(user.getUserId()) && user.getUserId() > 0 && user.getEnableStatus() == 1) {
                return true;
            }
        }
        PrintWriter writer = response.getWriter();
        writer.println("<html>");
        writer.println("<script>");
        writer.println("window.open (" + request.getContextPath() + "/schoolMallAuth/local/login?userType=2','_self");
        writer.println("</script>");
        writer.println("</html>");
        return false;
    }
}
